package com.wx.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wx.model.Books;
import com.wx.model.Cart;
import com.wx.model.Users;
import com.wx.service.BookService;
import com.wx.service.CartService;
import com.wx.serviceImpl.BookServiceImpl;
import com.wx.serviceImpl.CartServiceImpl;

/**
 * Servlet implementation class CartCheckServlet
 */
@WebServlet("/servlet/CartCheckServlet")
public class CartCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartCheckServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Users user=(Users)session.getAttribute("login");
		String username = user.getUsername();
		System.out.println("BookMsgServlet中username:"+username);
		CartService cartService=new CartServiceImpl();
		try {
			List<Cart> carts = cartService.checkCart(username);
			List<Books> books=new ArrayList<>();
			Books bookMsg = null;
			int cartcount = 0;
			double sum=0;
			for(int i=0;i<carts.size();i++){
				int bookid = carts.get(i).getBookid();
				cartcount = carts.get(i).getCartcount();
				System.out.println(bookid);
				if(bookid>0){
					BookService bookService=new BookServiceImpl();
					bookMsg = bookService.bookMsg(bookid,username);
					sum+=bookMsg.getPrice()*cartcount;
					books.add(bookMsg);
				}
			}
			System.out.println(sum);
			request.setAttribute("cartcount", cartcount);
			session.setAttribute("cartcount", cartcount);
			request.setAttribute("cartcheck", carts);
			request.setAttribute("sum", sum);
			request.setAttribute("books", books);
			session.setAttribute("books", books);
			request.getRequestDispatcher("../cart.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
